package controllers

import (
	"fmt"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"goravel/app/models"
	"goravel/app/services"
	"goravel/app/types"
	"goravel/app/utils"
)

type FileController struct {
	DbServer services.DBServer
}

func NewFileController() *FileController {
	return &FileController{
		DbServer: services.NewFileService(),
	}
}

// Index 文件列表
// @Summary      文件列表
// @Tags         File
// @Router       /file [get]
func (c *FileController) Index(ctx http.Context) http.Response {
	var files []models.File
	var filesResp []types.FileListResp
	query := facades.Orm().Query()
	//其他查询条件
	query = query.OrderBy("id", "desc")
	data, meta, err := c.DbServer.ListPage(ctx, &files, query, &filesResp)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).DataPage(data, meta)
}

// Show 文件详情
// @Summary      文件详情
// @Tags         File
// @Router       /file/{id} [get]
func (c *FileController) Show(ctx http.Context) http.Response {
	return services.NewApiService(ctx).OK("showed")
}

// Store 新增文件
// @Summary      新增文件
// @Tags         File
// @Router       /file [post]
func (c *FileController) Store(ctx http.Context) http.Response {
	file, err := ctx.Request().File("file")
	//TODO：文件类型校验
	if err != nil {
		return services.NewApiService(ctx).Error500("参数错误")
	}
	mimeType, _ := file.MimeType()
	fmt.Println("mimeType:", mimeType)
	allowedTypes := facades.Config().Get("app.allowed_file_types", []string{}).([]string)
	if !utils.Contains(allowedTypes, mimeType) {
		return services.NewApiService(ctx).Error500("文件类型错误")
	}
	originName := file.GetClientOriginalName()
	storagePath := "project/demo/" + carbon.Now().Format("2006-01-02")
	path, err := file.Store(storagePath)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	var model models.File
	model.OriginName = originName
	model.FileType = mimeType
	model.StorageName = path
	fmt.Println(model)
	err = facades.Orm().Query().Create(&model)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).OK("stored")
}

// Update 更新文件
// @Summary      更新文件
// @Tags         File
// @Router       /file/{id} [put]
func (c *FileController) Update(ctx http.Context) http.Response {
	return services.NewApiService(ctx).OK("updated")
}

// Destroy 删除文件
// @Summary      删除文件
// @Tags         File
// @Router       /file/{id} [delete]
func (c *FileController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt64("id")
	var record models.File
	err := facades.Orm().Query().FindOrFail(&record, id)
	if err != nil {
		return services.NewApiService(ctx).Error500("无相关数据")
	}
	_, err = facades.Orm().Query().Delete(&record)
	if err != nil {
		return services.NewApiService(ctx).Error500("删除失败")
	}
	//TODO：删除oss上文件
	return services.NewApiService(ctx).OK("deleted")
}
